package com.wugh.fast.demo.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.wugh.fast.module.api.vo.ResponseVO;
import com.wugh.fast.module.async.dto.CreateProcessDTO;
import com.wugh.fast.module.async.dto.CreateTaskDTO;
import com.wugh.fast.module.async.dto.Task;
import com.wugh.fast.module.async.dto.TaskProcessDetailDTO;
import com.wugh.fast.module.async.service.TaskService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Stream;

/**
 * 说明:
 *
 * @author wugh
 * @date 2020-04-14 10:10
 */
@Slf4j
@RestController
@RequestMapping("/api/task")
@Api(value = "/api/task", description = "任务测试")
public class TaskController {
    @Autowired
    private TaskService taskService;

    @PostMapping
    public ResponseVO<String> createTask(@RequestParam Long size, @RequestParam int time) {
        CreateTaskDTO create = new CreateTaskDTO();
        create.setCount(size);
        create.setName("测试任务");
        create.setType("test");
        Task task = taskService.startTask(create);
        ThreadUtil.execute(() -> {
            Stream.iterate(1, i -> ++i)
                    .limit(size)
                    .parallel()
                    .forEach(i -> {
                        CreateProcessDTO pro = new CreateProcessDTO();
                        pro.setTaskId(task.getId());
                        pro.setData(StrUtil.format("当前线程:{},序号:{}", Thread.currentThread().getName(), i));
                        taskService.startProcess(pro);
                        log.debug("序号:{},开始", i);
                        ThreadUtil.sleep(time);
                        taskService.finishProcess(task.getId(), pro.getOperator());
                        log.debug("序号:{},结束", i);
                    });
            taskService.finishTask(task.getId());
        });
        return ResponseVO.ok(task.getId());
    }

    @GetMapping("/{id}")
    public ResponseVO<TaskProcessDetailDTO> detail(@PathVariable String id) {
        return ResponseVO.ok(taskService.getTaskDetail(id));
    }
}
